package com.suyuan.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.suyuan.dao.CarinfoMapper;
import com.suyuan.dao.CompanyInfoMapper;
import com.suyuan.entity.CarInfo;
import com.suyuan.entity.CarInfoExample;
import com.suyuan.entity.CompanyInfo;
import com.suyuan.entity.CompanyInfoExample;
import com.suyuan.service.CarInfoService;
import com.suyuan.vo.CarInfoVO;
import com.suyuan.web.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 车辆管理业务类
 *
 */
@Service(value = "carInfoService")
@Transactional
public class CarInfoServiceImpl implements CarInfoService {

    @Resource
    private CarinfoMapper carinfoMapper;
    @Resource
    private CompanyInfoMapper companyInfoMapper;

    public List<CarInfoVO> list() {
        List<CarInfoVO> carInfoVOs = new ArrayList<CarInfoVO>();
        CarInfoExample example = new CarInfoExample();
        List<CarInfo> carInfos = carinfoMapper.selectByExample(example);
        for(CarInfo carInfo : carInfos){
            Integer comId = carInfo.getCompId();
            CompanyInfo companyInfo = companyInfoMapper.selectByPrimaryKey(comId);
            carInfoVOs.add(new CarInfoVO(carInfo,companyInfo));
        }
        return carInfoVOs;
    }

    public int add(CarInfo carInfo) {
        return carinfoMapper.insert(carInfo);
    }

    public int delete(Integer id) {
        return carinfoMapper.deleteByPrimaryKey(id);
    }

    /**
     * 模糊查询
     * @param licenseNumber
     * @param compName
     * @return
     */
    public PageInfo inquiry(String licenseNumber, String compName, Page page) {
        List<CarInfoVO> carInfoVOs = new ArrayList<CarInfoVO>();
        //两个条件都不为空的情况下
        if(StringUtils.isBlank(licenseNumber)){
            licenseNumber = null;//将空格、""等值直接用null替换掉
        }
        if(StringUtils.isBlank(compName)){
            compName = null;//将空格、""等值直接用null替换掉
        }

        PageHelper.startPage(page.getPageNumber(),page.getPageSize());
        List<CarInfo> cars = carinfoMapper.likeInquiry(licenseNumber,compName);
        PageInfo info = new PageInfo(cars);
        for(CarInfo car : (List<CarInfo>)info.getList()){
            CompanyInfo companyInfo = companyInfoMapper.selectByPrimaryKey(car.getCompId());
            carInfoVOs.add(new CarInfoVO(car,companyInfo));
        }
        info.setList(carInfoVOs);
        return info;
    }

    public CarInfo edit(Integer id) {
        return carinfoMapper.selectByPrimaryKey(id);
    }

    public int update(CarInfo carInfo) {
        return carinfoMapper.updateByPrimaryKey(carInfo);
    }

    public List<CompanyInfo> companyList() {
        return companyInfoMapper.selectByExample(new CompanyInfoExample());
    }

}
